package org.visionlibrary.image.errors;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.model.ImageProcessingError;


public class PeakMeanSquareError implements ImageProcessingError {
	@Override
	public float calculateError(TiledImage orig, TiledImage proc) {
		if(orig.getWidth() != proc.getWidth())
			return -1; //TODO rzucac wyjatkiem
		
		if(orig.getHeight() != proc.getHeight())
			return -1;
		
		if(orig.getNumBands() != proc.getNumBands())
			return -1;
		
		int maxX = orig.getWidth();
		int maxY = orig.getHeight();
		int channels = orig.getNumBands();
		
		float[] sums = new float[orig.getNumBands()];
		float[] max = new float[orig.getNumBands()];
		
		for(int x=0; x < maxX; x++)
			for(int y=0; y < maxY; y++)
				for(int b=0; b < channels; b++) {
					float origp = orig.getSampleFloat(x, y, b);
					if(origp > max[b])
						max[b] = origp;
				}
		
		for(int x=0; x < maxX; x++)
			for(int y=0; y < maxY; y++)
				for(int b=0; b < channels; b++) {
					float origp = orig.getSampleFloat(x, y, b);
					float procp = proc.getSampleFloat(x, y, b);
					float diff = origp - procp;
					sums[b] = (diff * diff) / (max[b] * max[b]);
					
				}
		
		float sum = 0;
		for(int i=0; i < channels; i++)
			sum += sums[i];
		
		sum /= channels;
		
		return sum / (maxX * maxY);
	}

}
